package com.sendtion.xrichtextdemo.slice;

import com.sendtion.xrichtext.RichTextView;
import com.sendtion.xrichtextdemo.ResourceTable;
import com.sendtion.xrichtextdemo.bean.Note;
import com.sendtion.xrichtextdemo.utils.DialogUtil;
import com.sendtion.xrichtextdemo.utils.MyToast;
import com.sendtion.xrichtextdemo.utils.StringUtils;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.RoundProgressBar;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.utils.net.Uri;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * NoteAbilitySlice
 *
 * @since 2021-06-22
 */
public class NoteAbilitySlice extends AbilitySlice {
    private static final int TITLE_COLOR = -13615201;
    private static final int INT_10 = 10;
    private static final int INT_100 = 100;
    private static final int INT_6 = 6;
    private static final int INT_7 = 7;
    private Note note;
    private Text share;
    private Text redact;
    private Text title;
    private Text time;
    private Text group;
    private DirectionalLayout back;
    private RichTextView tvnotecontent;
    private String myTitle;
    private String myContent;
    private String myGroupName;
    private String myCreateTime;
    private Timer timer;
    private int progress = 0;
    private CommonDialog toastDialog;
    private Disposable mDisposable;
    private List<Uri> dataList;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_note);
        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(TITLE_COLOR);
        noteInit(intent);
    }

    private void noteInit(Intent intent) {
        note = intent.getSerializableParam("note");
        share = (Text) findComponentById(ResourceTable.Id_action_insert_image);
        redact = (Text) findComponentById(ResourceTable.Id_action_new_save);
        title = (Text) findComponentById(ResourceTable.Id_et_note_title);
        time = (Text) findComponentById(ResourceTable.Id_tv_note_time);
        group = (Text) findComponentById(ResourceTable.Id_tv_note_group);
        tvnotecontent = (RichTextView) findComponentById(ResourceTable.Id_et_new_content);
        back = (DirectionalLayout) findComponentById(ResourceTable.Id_back);

        back.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onBackPressed();
            }
        });

        share.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                MyToast.show(getContext(), "暂不支持此功能", MyToast.ToastLayout.BOTTOM);
            }
        });

        redact.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                Intent intent = new Intent();
                intent.setParam("groupName", "默认笔记");
                intent.setParam("flag", 1);
                intent.setParam("note", note);
                Operation operationBuilder = new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(getBundleName())
                        .withAbilityName("com.sendtion.xrichtextdemo.NewAbility")
                        .build();
                intent.setOperation(operationBuilder);
                startAbility(intent);
                terminateAbility();
            }
        });

        setData();
    }

    private void setData() {
        if (note != null) {
            myTitle = note.getTitle();
            myContent = note.getContent();
            myGroupName = note.getGroupName();
            myCreateTime = note.getCreateTime();

            title.setText(myTitle);
            time.setText(myCreateTime);
            group.setText(myGroupName);
            dealWithContent();
        }
    }

    private void dealWithContent() {
        tvnotecontent.clearAllLayout();
        showDataSync(myContent);

        tvnotecontent.setOnRtImageClickListener(new RichTextView.OnRtImageClickListener() {
            @Override
            public void onRtImageClick(String imagePath) {
                ArrayList<String> imageList = StringUtils.getTextFromHtml(myContent, true);
                int currentPosition = imageList.indexOf(imagePath);
                MyToast.show(getContext(), "点击图片" + currentPosition + ": " + imagePath,
                        MyToast.ToastLayout.BOTTOM);
                dataList = new ArrayList<>();
                for (int i = 0; i < imageList.size(); i++) {
                    dataList.add(getUriFromPath(imageList.get(i)));
                }
                DialogUtil.show(getContext(), dataList, currentPosition);
            }
        });
    }

    private void showListContainerDialog(int index) {
        CommonDialog commonDialog = new CommonDialog(this);
        Component component = LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_dialog_listcontainer, null, false);
        Text position = (Text) component.findComponentById(ResourceTable.Id_now_position);
        Text max = (Text) component.findComponentById(ResourceTable.Id_now_max);
        max.setText("/" + dataList.size());
        position.setText(index + "");
        commonDialog.setContentCustomComponent(component);
        commonDialog.show();
        ListContainer listContainer = (ListContainer) component
                .findComponentById(ResourceTable.Id_dialog_listcontainer);
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                commonDialog.remove();
            }
        });
        listContainer.setScrollListener(new ListContainer.ScrollListener() {
            @Override
            public void onScrollFinished() {
                int firstVisibleItemPosition = listContainer.getFirstVisibleItemPosition();
                position.setText(firstVisibleItemPosition + 1 + "");
            }
        });
    }

    private Uri getUriFromPath(String imagePath) {
        Uri uri = null;
        if (!imagePath.isEmpty()) {
            if (imagePath.startsWith("http")) {
                uri = Uri.parse(imagePath);
            } else {
                File file = new File(imagePath);
                if (file.exists()) {
                    uri = Uri.getUriFromFile(file);
                }
            }
        }
        return uri;
    }

    /**
     * 异步方式显示数据
     *
     * @param html
     */
    private void showDataSync(final String html) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(@NotNull ObservableEmitter<String> emitter) throws Exception {
                showEditData(emitter, html);
            }
        })
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NotNull Disposable disposable) {
                        mDisposable = disposable;
                    }

                    @Override
                    public void onNext(@NotNull String text) {
                        if (tvnotecontent != null) {
                            if (text.contains("<img") && text.contains("src=")) {
                                String imagePath = StringUtils.getImgSrc(text);
                                tvnotecontent.addImageViewAtIndex(tvnotecontent.getLastIndex(), imagePath);
                            } else {
                                tvnotecontent.addTextViewAtIndex(tvnotecontent.getLastIndex(), text);
                            }
                        }
                    }

                    @Override
                    public void onError(@NotNull Throwable throwable) {
                        if (toastDialog != null) {
                            toastDialog.remove();
                        }

                        new ToastDialog(NoteAbilitySlice.this).setContentText("解析错误：图片不存在或已损坏").show();
                    }

                    @Override
                    public void onComplete() {
                        if (toastDialog != null) {
                            toastDialog.remove();
                        }
                    }
                });
    }

    /**
     * 显示数据
     *
     * @param emitter
     * @param html
     */
    private void showEditData(ObservableEmitter<String> emitter, String html) {
        try {
            List<String> textList = StringUtils.cutStringByImgTag(html);
            for (int i = 0; i < textList.size(); i++) {
                String text = textList.get(i);
                emitter.onNext(text);
            }
            emitter.onComplete();
        } catch (Exception e) {
            e.getMessage();
            emitter.onError(e);
        }
    }

    private void openDialog() {
        Component component = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_progress_layout, null, false);
        RoundProgressBar bar = (RoundProgressBar) component.findComponentById(ResourceTable.Id_bar);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                bar.setProgressValue(progress);
                progress += INT_10;
                if (progress == INT_100) {
                    progress = 0;
                }
            }
        }, 0, INT_100);
        toastDialog = new CommonDialog(this);
        toastDialog.setContentCustomComponent(component);
        toastDialog.setAutoClosable(false);
        toastDialog.setSize(DisplayManager.getInstance().getDefaultDisplay(this)
                .get().getAttributes().width / INT_7 * INT_6, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        toastDialog.setAlignment(LayoutAlignment.CENTER);
        toastDialog.show();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
